<?php

class UsersController extends AppController {

    public $name = 'Users';
    public $uses = array('User', 'UserRole', 'Menu', 'UserRoleMenu', 'UserAction', 'Department');
    public $helpers = array('Tree', 'Paginator');
    public $paginate = array(
        'UserAction' => array(
            'limit' => 25,
            'order' => array('UserAction.id' => 'desc')
        )
    );

    function beforeFilter() {
        if( $this->action != "admin_login" && $this->action != "admin_logout" ) {
            if( $this->Session->check('user') == false ) {
                $this->redirect('/admin/users/login/');
            }
        }
    }

    public function admin_index() {
        $user = $this->Session->read('user');

        $user_menus = $this->UserRoleMenu->find('list', array(
            'fields' => array("menu_id"),
            'conditions' => array('user_role_id' => $user['User']['user_role_id']),
            'recursive' => -1
                ));

        $menus = $this->Menu->find('all', array(
            'conditions' => array('id' => $user_menus, 'level' => 3, 'parent_id' => 1),
            'recursive' => -1,
            'order' => array('position')
                ));

        $this->set('menus', $menus);
    }

    /**
     * Logs in a user and redirects them to the right applications section
     */
    public function admin_login() {
        $this->layout = "login_layout";

        if( isset($_POST['username']) ) {
            $user = $this->User->findForLogin($_POST['username'], $_POST['password']);

            if( $user ) {
                $this->User->updateLogin($user['User']['id']);
                $this->Session->write('user', $user);
                $this->redirect('/admin/dashboard');
            } else {
                $this->redirect('/admin/users/login?error');
            }
        }
    }

    /**
     * Logs the current user out of the system
     */
    public function admin_logout() {
        $user = $this->Session->read('user');
        $this->User->updateLogout($user['User']['id']);

        $this->Session->delete('user');
        $this->redirect('/admin/users/login');
    }

    function admin_manage() {
        $roles = $this->UserRole->getUserRoles();

        $this->set('roles', $roles);
    }

    function admin_view($id = null) {
        if( !$id ) {
            $this->Session->setFlash(__('Invalid user', true));
            $this->redirect(array('action' => 'index'));
        }
        $user = $this->User->find('first', array(
            'contain' => array('UserRole'),
            'conditions' => array('User.id' => $id)
                ));

        $this->set('user', $user);
    }

    function admin_add() {
        if( !empty($this->data) ) {

            if( $this->User->createNewUser() ) {
                //$this->Session->setFlash(__('The user has been saved', true));
                //$this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
            }
        }

        $this->layout = "empty";

        $roles = $this->UserRole->getUserRoles();
        $departments = $this->Department->find('all', array('order' => array('name'), 'recursive' => -1));

        $this->set('roles', $roles);
        $this->set('departments', $departments);
    }

    function admin_add_user_role() {

        $this->layout = "empty";

        if( !empty($this->data) ) {

            $this->UserRole->create();

            if( $this->UserRole->save($this->data) ) {

                $this->redirect(array('action' => 'admin_roles_list'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
            }
        }
    }

    function admin_edit($id = null) {
        if( !$id && empty($this->data) ) {
            $this->Session->setFlash(__('Invalid user', true));
            $this->redirect(array('action' => 'index'));
        }
        if( !empty($this->data) ) {
            if( $this->User->save($this->data) ) {
                $this->Session->setFlash(__('The user has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
            }
        }
        if( empty($this->data) ) {
            $this->data = $this->User->find('first', array(
                'conditions' => array('User.id' => $id),
                'recursive' => -1
                    ));
        }

        $roles = $this->UserRole->getUserRoles();
        $departments = $this->Department->find('all', array('order' => array('name'), 'recursive' => -1));

        $this->set('roles', $roles);
        $this->set('departments', $departments);

        $this->layout = "empty";
    }

    function admin_delete($id = null) {
        if( !$id ) {
            $this->Session->setFlash(__('Invalid id for user', true));
            $this->redirect(array('action' => 'index'));
        }
        if( $this->User->delete($id) ) {
            $this->Session->setFlash(__('User deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('User was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

    function admin_delete_role($id = null) {
        if( !$id ) {
            $this->Session->setFlash(__('Invalid id for user', true));
            $this->redirect(array('action' => 'index'));
        }

        if( $this->UserRole->delete($id) ) {
            $this->Session->setFlash(__('User deleted', true));
        }
    }

    function admin_delete_selected() {

        if( $this->RequestHandler->isAjax() ) {
            $this->autoRender = false;

            $this->User->deleteAll(array('User.id' => explode(",", $_POST['ids'])));
        }
    }

    public function admin_loadRoleUsers($role_id) {
        $this->layout = "empty";

        $users = $this->User->find('all', array(
            'conditions' => array('user_role_id' => $role_id),
            'order' => array('first_name'),
            'recursive' => -1
                ));

        $this->set('users', $users);
    }

    function admin_roles() {

        $roles = $this->UserRole->getUserRoles();

        $menus = $this->Menu->find("threaded", array(
            'order' => array('position'),
            'recursive' => -1
                ));

        $this->set("menus", $menus);
        $this->set('roles', $roles);
    }

    function admin_roles_list() {
        $this->set('roles', $this->UserRole->find('all', array('recursive' => -1, 'order' => array('name'))));
    }

    function admin_role_menus() {

        if( $this->RequestHandler->isAjax() ) {

            if( isset($_POST['menu_ids']) ) {

                $posted_menus = explode(",", $_POST['menu_ids']);

                $selected_menus = $this->UserRoleMenu->find('list', array(
                    'fields' => array('menu_id'),
                    'conditions' => array('user_role_id' => $_POST['user_role_id'])
                        ));

                # get the old menus deselected from the role
                $menusToRemove = array_diff(array_values($selected_menus), $posted_menus);

                $this->UserRoleMenu->deleteAll(array('user_role_id' => $_POST['user_role_id'], 'menu_id' => $menusToRemove));

                # get the new menus selected for the role
                $menusToAdd = array_diff($posted_menus, array_values($selected_menus));

                $data = array();

                foreach( $menusToAdd as $menu ) {
                    $data[] = array(
                        'UserRoleMenu' => array(
                            'user_role_id' => $_POST['user_role_id'],
                            'menu_id' => $menu
                        )
                    );
                }

                $this->UserRoleMenu->saveAll($data);
            } else {
                $this->autoRender = false;
                $role_menus = $this->UserRoleMenu->find("all", array(
                    'conditions' => array('user_role_id' => $_POST['user_role_id'])
                        ));

                echo json_encode($role_menus);
            }
        }
    }

    function admin_edit_role($id = NULL) {

        if( !$id ) {
            echo __("Role ID Not Specified");
            return;
        }

        if( isset($_POST['data']) ) {
            //$this->autoRender = false;

            if( $this->UserRole->save($_POST['data']) ) {
                //$this->Session->setFlash(__('The user has been saved', true));
                $this->redirect(array('action' => 'admin_roles_list'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
            }
        }

        if( empty($this->data) ) {
            $this->data = $role = $this->UserRole->read(null, $id);

            $this->set('role', $role);
        }
    }

    public function admin_audit_trail() {

        $users = $this->User->find('all', array(
            'fields' => array('id', 'first_name', 'last_name', 'last_access_dt'),
            //'conditions' => array('user_role_id <>' => 1),
            'order' => array('last_name'),
            'recursive' => -1)
        );

        $this->set('users', $users);
    }

    public function admin_audit_list() {

        $user_id = $_POST['user_id'];

        $this->set('userActions', $this->paginate('UserAction', array('user_id' => $user_id)));
    }

    public function admin_audit_search() {

        $conditions = array();

        if( isset($_POST['action_desc']) ) {
            $conditions['UserAction.action_desc LIKE'] = "%" . $_POST['action_desc'] . "%";
        }

        if( isset($_POST['start_dt']) && $_POST['start_dt'] != "" ) {
            if( isset($_POST['end_dt']) && $_POST['end_dt'] != "" ) {
                $conditions['UserAction.action_dt BETWEEN ? AND ? '] = array($_POST['start_dt'], $_POST['end_dt']);
            } else {
                $conditions['UserAction.action_dt'] = $_POST['start_dt'];
            }
        }

        $userActions = $this->UserAction->find('all', array(
            'contain' => array(
                'User' => array(
                    'fields' => array('first_name', 'last_name')
                )
            ),
            'conditions' => $conditions,
            'order' => array('UserAction.id' => 'desc'),
            'limit' => 50
                ));

        $this->set('userActions', $userActions);
    }

    public function admin_departments() {

        $department = ClassRegistry::init('Department');

        $departments = $department->find('all', array(
            'contain' => array(
                'DepartmentSupervisor' => array(
                    'User' => array(
                        'fields' => array('first_name', 'last_name')
                    ),
                    'conditions' => array('deleted' => 0)
                )
            ),
            'order' => array('name')
                ));

        $users = $this->User->find('all', array(
            'recursive' => -1
                ));

        $this->set('departments', $departments);
        $this->set('users', $users);
    }

    public function admin_check_old_oldpasss() {
        $username = $_POST['username'];
        $password = $_POST['password'];
        $user = $this->User->findForLogin($username, $password);
        if( $user ) {
            echo json_encode(array("status" => "true"));
        } else {
            echo json_encode(array("status" => "false"));
        }
        exit();
    }

    public function admin_reset_pass() {
        $userid = $_POST['userid'];
        $password = md5($_POST['password']);
        $user = array();
        $user['User']['id'] = $userid;
        $user['User']['password'] = $password;
        $this->User->save($user);
        echo json_encode(array("status" => "true"));
        exit();
    }
    
    public function admin_purge_actions() {
        $this->autoRender = false;
        
        $this->UserAction->purgeActions();
    }

}

?>